package com.ruoyi.dataSet.http;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.dataSet.DTO.DatasetCreateRequest;
import com.ruoyi.dataSet.DTO.DocumentCreateRequest;
import com.ruoyi.dataSet.DTO.DocumentUpdateRequest;
import com.ruoyi.dataSet.DTO.DocumentCreateByFileRequest;
import okhttp3.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class HttpClient {

    private static final String API_URL = "http://127.0.0.1:88/v1"; // 基础 URL
    private static final String API_KEY = "dataset-K3u3beBG8fcO3ss4urRhdbwM"; // 替换为实际 API Key
    private static final OkHttpClient client = new OkHttpClient.Builder()
        .connectTimeout(100, TimeUnit.SECONDS)
        .readTimeout(100, TimeUnit.SECONDS)
        .writeTimeout(100, TimeUnit.SECONDS)
        .build();

    // 文本创建文档
    public static String createDocument(String datasetId, DocumentCreateRequest request) throws IOException {
        StringBuilder jsonBodyBuilder = new StringBuilder("{");

        if (request.getName() != null && !request.getName().isEmpty()) {
            jsonBodyBuilder.append("\"name\": \"").append(request.getName()).append("\",");
        }

        if (request.getText() != null && !request.getText().isEmpty()) {
            jsonBodyBuilder.append("\"text\": \"").append(request.getText()).append("\",");
        }

        if (request.getDocType() != null && !request.getDocType().isEmpty()) {
            jsonBodyBuilder.append("\"doc_type\": \"").append(request.getDocType()).append("\",");
        }

        if (request.getDocMetadata() != null && !request.getDocMetadata().isEmpty()) {
            jsonBodyBuilder.append("\"doc_metadata\": \"").append(request.getDocMetadata()).append("\",");
        }

        if (request.getIndexingTechnique() != null && !request.getIndexingTechnique().isEmpty()) {
            jsonBodyBuilder.append("\"indexing_technique\": \"").append(request.getIndexingTechnique()).append("\",");
        }
        // 处理 process_rule
        if (request.getProcessRule() != null) {
            jsonBodyBuilder.append("\"process_rule\": {");
            // mode
            if (request.getProcessRule().getMode() != null && !request.getProcessRule().getMode().isEmpty()) {
                jsonBodyBuilder.append("\"mode\": \"").append(request.getProcessRule().getMode()).append("\"");
            }
            jsonBodyBuilder.append("},");
        }

        // Remove the last comma if there is one
        if (jsonBodyBuilder.charAt(jsonBodyBuilder.length() - 1) == ',') {
            jsonBodyBuilder.deleteCharAt(jsonBodyBuilder.length() - 1);
        }

        jsonBodyBuilder.append("}");

        String jsonBody = jsonBodyBuilder.toString();
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonBody);

        System.out.println("jsonBody: " + jsonBody);
        Request requestObj = new Request.Builder()
            .url(API_URL + "/datasets/" + datasetId + "/document/create-by-text")
            .header("Authorization", "Bearer " + API_KEY)
            .header("Content-Type", "application/json")
            .post(body)
            .build();

        try (Response response = client.newCall(requestObj).execute()) {
            System.out.println("response:"+response);
            return response.body().string();
        }
    }

    // 获取文档列表
    public static String getDocuments(String datasetId, String page, String limit) throws IOException {
        HttpUrl url = HttpUrl.parse(API_URL + "/datasets/" + datasetId + "/documents")
            .newBuilder()
            .addQueryParameter("page", page != null && !page.isEmpty() ? page : "1")
            .addQueryParameter("limit", limit != null && !limit.isEmpty() ? limit : "20")
            .build();

        Request request = new Request.Builder()
            .url(url)
            .header("Authorization", "Bearer " + API_KEY)
            .header("Content-Type", "application/json")
            .get()
            .build();

        System.out.println("url:"+url);
        System.out.println("request:"+request);
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    // 通过文件创建文档
    public static String createDocumentByFile(String datasetId, String data, MultipartFile file) throws IOException {
        OkHttpClient client = new OkHttpClient();

        // 构建 multipart 请求体
        MultipartBody.Builder multipartBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        multipartBuilder.addFormDataPart("data", data);

        // 添加文件部分
        RequestBody fileBody = RequestBody.create(MediaType.parse(file.getContentType()), file.getBytes());
        multipartBuilder.addFormDataPart("file", file.getOriginalFilename(), fileBody);

        RequestBody requestBody = multipartBuilder.build();

        // 构建请求
        Request requestObj = new Request.Builder()
            .url(API_URL+"/datasets/" + datasetId + "/document/create-by-file")
            .header("Authorization", "Bearer dataset-K3u3beBG8fcO3ss4urRhdbwM")
            .post(requestBody)
            .build();

        try (Response response = client.newCall(requestObj).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected response: " + response.code() + " - " + response.body().string());
            }
            return response.body().string();
        }
    }



    // 删除文档
    public static String deleteDocument(String datasetId, String documentId) throws IOException {
        Request request = new Request.Builder()
            .url(API_URL + "/datasets/" + datasetId + "/documents/" + documentId)
            .header("Authorization", "Bearer " + API_KEY)
            .header("Content-Type", "application/json")
            .delete()
            .build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    // 更新文档
    public static String updateDocument(String datasetId, String documentId, DocumentUpdateRequest request) throws IOException {
        StringBuilder jsonBodyBuilder = new StringBuilder("{");

        if (request.getName() != null && !request.getName().isEmpty()) {
            jsonBodyBuilder.append("\"name\": \"").append(request.getName()).append("\",");
        }

        if (request.getText() != null && !request.getText().isEmpty()) {
            jsonBodyBuilder.append("\"text\": \"").append(request.getText()).append("\",");
        }

        if (request.getDocType() != null && !request.getDocType().isEmpty()) {
            jsonBodyBuilder.append("\"doc_type\": \"").append(request.getDocType()).append("\",");
        }

        if (request.getDocMetadata() != null && !request.getDocMetadata().isEmpty()) {
            jsonBodyBuilder.append("\"doc_metadata\": \"").append(request.getDocMetadata()).append("\",");
        }

        // Remove the last comma if there is one
        if (jsonBodyBuilder.charAt(jsonBodyBuilder.length() - 1) == ',') {
            jsonBodyBuilder.deleteCharAt(jsonBodyBuilder.length() - 1);
        }

        jsonBodyBuilder.append("}");

        String jsonBody = jsonBodyBuilder.toString();
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonBody);

        Request requestObj = new Request.Builder()
            .url(API_URL + "/datasets/" + datasetId + "/documents/" + documentId + "/update-by-text")
            .header("Authorization", "Bearer " + API_KEY)
            .header("Content-Type", "application/json")
            .post(body)
            .build();

        try (Response response = client.newCall(requestObj).execute()) {
            return response.body().string();
        }
    }

    // 创建知识库
    public static String createDataset(DatasetCreateRequest request) throws IOException {
        StringBuilder jsonBodyBuilder = new StringBuilder("{");

        if (request.getName() != null && !request.getName().isEmpty()) {
            jsonBodyBuilder.append("\"name\": \"").append(request.getName()).append("\",");
        }

        if (request.getDescription() != null && !request.getDescription().isEmpty()) {
            jsonBodyBuilder.append("\"description\": \"").append(request.getDescription()).append("\",");
        }

        if (request.getIndexingTechnique() != null && !request.getIndexingTechnique().isEmpty()) {
            jsonBodyBuilder.append("\"indexing_technique\": \"").append(request.getIndexingTechnique()).append("\",");
        }

        if (request.getPermission() != null && !request.getPermission().isEmpty()) {
            jsonBodyBuilder.append("\"permission\": \"").append(request.getPermission()).append("\",");
        }

        if (request.getProvider() != null && !request.getProvider().isEmpty()) {
            jsonBodyBuilder.append("\"provider\": \"").append(request.getProvider()).append("\",");
        }

        // Remove the last comma if there is one
        if (jsonBodyBuilder.charAt(jsonBodyBuilder.length() - 1) == ',') {
            jsonBodyBuilder.deleteCharAt(jsonBodyBuilder.length() - 1);
        }

        jsonBodyBuilder.append("}");

        String jsonBody = jsonBodyBuilder.toString();
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonBody);

        System.out.println("jsonBody: " + jsonBody);
        Request requestObj = new Request.Builder()
            .url(API_URL + "/datasets")
            .header("Authorization", "Bearer " + API_KEY)
            .header("Content-Type", "application/json")
            .post(body)
            .build();

        try (Response response = client.newCall(requestObj).execute()) {
            return response.body().string();
        }
    }

    // 获取知识库列表
    public static String getDatasets(String page, String limit) throws IOException {
        HttpUrl url = HttpUrl.parse(API_URL + "/datasets")
            .newBuilder()
            .addQueryParameter("page", page != null && !page.isEmpty() ? page : "1")
            .addQueryParameter("limit", limit != null && !limit.isEmpty() ? limit : "20")
            .build();

        Request request = new Request.Builder()
            .url(url)
            .header("Authorization", "Bearer " + API_KEY)
            .header("Content-Type", "application/json")
            .get()
            .build();

        try (Response response = client.newCall(request).execute()) {
            System.out.println("response: " + response);
            if (response.body() != null) {
                return response.body().string();
            }
            else {
                return ("response为空");
            }
        }
    }

    // 删除知识库
    public static String deleteDataset(String datasetId) throws IOException {
        Request request = new Request.Builder()
            .url(API_URL + "/datasets/" + datasetId)
            .header("Authorization", "Bearer " + API_KEY)
            .header("Content-Type", "application/json")
            .delete()
            .build();

        try (Response response = client.newCall(request).execute()) {
            AjaxResult result = AjaxResult.success();
            // 判断响应码
            if (response.code() == 204) {
                result.put("code", 200);
                result.put("msg", "删除成功");
                // 204表示操作成功，但无返回内容
                return result.toString();  // 成功信息
            } else {
                result.put("code", 500);
                result.put("msg", "系统繁忙，请刷新后重试");
                // 如果返回其他响应码，表示操作失败
                return result.toString();
            }
        }
    }

    // 获取知识库状态
    public static String getDatasetStatus(String datasetId) throws IOException {
        Request request = new Request.Builder()
            .url(API_URL + "/datasets/" + datasetId + "/status")
            .header("Authorization", "Bearer " + API_KEY)
            .header("Content-Type", "application/json")
            .get()
            .build();
        try (Response response = client.newCall(request).execute()) {
            System.out.println("response: " + response);
            return response.body().string();
        }
    }


}
